<?php
namespace app\admin\controller;
use think\Verify;
use think\facade\Db;
use app\common\controller\CommonBase;

class Base extends CommonBase {
    public $sid = 0;
    /**
     * 初始化操作
     */
    public function initialize()
    {

        parent::initialize();
        if(!defined('SID')){
            define('SID', session('suppliers_id'));
        }

        //过滤不需要登陆的行为
        if (!in_array(request()->action(), array('yiqigou', 'vertify','che32432ckp2'))) {
            if (session('admin_id') <= 0) {
                return ['status'=>0,'msg'=>'请先登录','url'=>url('Admin/yiqigou')];
            }
        }
        if(session('?expire_time') && session('expire_time')<time()){
            session(null);
            $this->redirect( url('Admin/yiqigou'));
        }

        //判断二级密码
        $judge = request()->controller().'-'.request()->action();
        $pary = [
            'Users-index',
            'Users-glnet',
            'UserLevel-index',
            'LevelLog-edit',
            'LevelLog-index',
            'System-index',
            'SysLog-index',
            'RechargeLog-index',
            'Withdrawals-index',
            'TransferSet-index',
            'Goods-index',
            'Order-index',
            'Admin-role',
            //'Admin-index',
            'Tools-restore',
            'TuanPeriods-index',
            'Weihu-chushiDb66del',
        ];
        if(!session('?sys_checkpwd2')) {
//            if(in_array($judge,$pary)){
//                $_SESSION['sys_checkpwd_par']=array(CONTROLLER_NAME,ACTION_NAME);
//                $this->redirect( U('Admin/che32432ckp2'));
//            }
        }
        $sid = defined('SID')?SID:0;
        if($sid==0){
            //$sid = Db::name('suppliers')->where('is_plate',1)->value('id');
        }
        $this->sid = $sid;

    }

    public function check_priv()
    {
    	$ctl = CONTROLLER_NAME;
    	$act = ACTION_NAME;
        $act_list = session('act_list');
		//无需验证的操作
		$uneed_check = array('yiqigou','logout','vertify','imageUp','upload','videoUp','delupload','initAdmin');
		//无需验证的模块
		$noctl = ['Index','Weihu','Plugin'];
    	if((in_array($ctl,$noctl) && $act!='changeTableVal') || $act_list == 'all'){
    		//后台首页控制器无需验证,超级管理员无需验证
    		return true;
    	}elseif(in_array($act,$uneed_check)){
    		return true;
    	}else{
            $role_right = Db::name('system_menu')->where("id", "in", $act_list)->cache(true)->column('right');
            $admin = Db::name('admin')->where('admin_id',session('admin_id'))->find();
            if($admin['id']==1){
                //超级管理员不用验证
                return true;
            }
    		//检查是否拥有此操作权限
            $op = $ctl.'@'.$act;
    		if(!in_array($op, $role_right) && !in_array($ctl.'@*', $role_right)){
    		    $have = false;
    		    foreach($role_right as $right){
    		        if(strstr($right,$op)){
                        $have=true;
                    }
                }
                if(!$have && $admin['is_admin']!=1){
    		        if(CONTROLLER_NAME=='Admin' && ACTION_NAME=='welcome'){
                        $this->redirect(U('Index/welcome'));
                    }
    		        //return json(['status'=>0,'msg'=>'您没有操作权限,请联系超级管理员分配权限']);
    			    $this->error('您没有操作权限,请联系超级管理员分配权限'.$op,U('Index/welcome'));
                }
    		}
    	}
    }

    /**
     * 验证码获取
     */
    public function vertify()
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => false,
            'useNoise' => false,
            'reset' => true
        );
        $Verify = new Verify($config);
        $Verify->entry("admin_login");
        exit();
    }


    /**
     * ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
     * table,id_name,id_value,field,value
     */
    public function changeTableVal()
    {
        $table = I('table'); // 表名
        $id_name = I('id_name'); // 表主键id名
        $id_value = I('id_value'); // 表主键id值
        $field = I('field'); // 修改哪个字段
        $value = I('value'); // 修改字段值
        Db::name($table)->where([$id_name => $id_value])->save(array($field => $value)); // 根据条件保存修改的数据
    }

    //导出
    public function export($group,$lists,$filename){
        $strTable ='<table width="700" border="1">';
        $strTable .= '<tr>';
        foreach($group as $name){
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">'.$name.'</td>';
        }

        $strTable .= '</tr>';

        foreach($lists as $k=>$val){
            $strTable .= '<tr>';
            foreach($group as $field=>$name) {
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val[$field] . '</td>';
            }
            $strTable .= '</tr>';
        }

        $strTable .='</table>';
        unset($lists);
        downloadExcel($strTable,$filename);
        exit();
    }
    function export_excel(array $titleArr,array $dataArr,array $typeArr=[]){
        $phpexcel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();//实例化
        $phpsheet = $phpexcel->getActiveSheet();
        //填充表头信息
        $widthArr = [];
        for($i = 0;$i < count($titleArr);$i++) {
            $phpsheet->setCellValue(IntToChr($i)."1","$titleArr[$i]");
            $widthArr[] = strlen($titleArr[$i]);
        }
        //填充表格信息
        for ($i = 2;$i <= count($dataArr) + 1;$i++) {
            $j = 0;
            foreach ($dataArr[$i-2] as $key=>$value) {
                if($typeArr && $typeArr[$j] == 1)//数字
                    $phpsheet->setCellValue(IntToChr($j)."$i","$value");
                else
                    $phpsheet->setCellValueExplicit(IntToChr($j)."$i","$value",\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
                if(strlen($value) > $widthArr[$j]){
                    $widthArr[$j] = strlen($value);
                    if($widthArr[$j] > 25) $widthArr[$j] = 25;
                }
                $j++;
            }
        }
        //设置列宽
        foreach($widthArr as $k=>$v){
            $phpsheet->getColumnDimension(IntToChr($k))->setWidth($v+2);
        }
        $phpwriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($phpexcel,"Xlsx");
        header('Content-Disposition: attachment;filename="'.date('YmdHis').'.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $phpwriter->save("php://output");
        die();
    }
    function import_excel($file='', $startrow=2){
        if(strpos(PRE_URL,$file)==0){
            $file = ROOT_PATH.ltrim(str_replace(PRE_URL,'',$file),'/');
        }
        $file = iconv("utf-8", "gb2312", $file);   //转码
        if(empty($file) OR !file_exists($file)) {
            echojson(['status'=>0,'msg'=>'file not exists!']);
        }
        $objRead = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');   //建立reader对象
        if(!$objRead->canRead($file)){
            $objRead = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
            if(!$objRead->canRead($file)){
                echojson(['status'=>0,'msg'=>'No Excel!']);
            }
        }
        $PHPExcel = $objRead->load($file);
        $currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表
        $allColumn = $currentSheet->getHighestColumn(); //取得最大的列号
        $allColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($allColumn);
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $exceldata = array();
        /**从第二行开始输出，因为excel表中第一行为列名*/
        for($currentRow = $startrow;$currentRow <= $allRow;$currentRow++){
            /**从第A列开始输出*/
            $erp_orders_id = array();  //声明数组
            for($currentColumn= 1;$currentColumn<= $allColumn; $currentColumn++){
                $val = $currentSheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue();/**ord()将字符转为十进制数*/
                $erp_orders_id[] = $val;
            }
            $exceldata[] = $erp_orders_id;
        }
        return $exceldata;
    }

}